package com.cangxuan.app.ui.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cangxuan.app.R;
import com.cangxuan.app.adapter.MarketGoodsAdapter;
import com.cangxuan.app.entity.Goods;
import com.cangxuan.app.entity.Issuer;
import com.cangxuan.app.entity.MarketGoods;
import com.cangxuan.app.entity.Series;
import com.cangxuan.app.ui.collection.CollectionDetailActivity;
import com.cangxuan.app.utils.DBUtils;
import com.cangxuan.app.utils.DeviceUtils;
import com.cangxuan.app.utils.GridViewUtils;
import com.cangxuan.app.utils.HttpUtils;
import com.cangxuan.app.utils.UserUtils;

import java.io.File;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 市场fragment
 * author:何程城
 */
public class MarketFragment extends Fragment {

    /**
     * 发行方适配器
     */
    public class IssuerAdapter extends BaseAdapter {
        private List<Issuer> issuerList;

        public IssuerAdapter(List<Issuer> issuerList) {
            this.issuerList = issuerList;
        }

        @Override
        public int getCount() {
            return issuerList.size();
        }

        @Override
        public Object getItem(int i) {
            return issuerList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return issuerList.get(i).getId();
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            // 声明视图持有类实例
            ViewHolder viewHolder;
            if (view == null) {
                // 实例view对象
                view = LayoutInflater.from(getContext()).inflate(R.layout.activity_market_filter_item, viewGroup, false);
                viewHolder = new ViewHolder();
                viewHolder.issuer = view.findViewById(R.id.filterItem);
                view.setTag(viewHolder);
            } else {
                // 当ListView后面再获取项的视图时
                viewHolder = (ViewHolder) view.getTag();
            }
            // 先取出对应下标的Goods
            Issuer issuer = issuerList.get(i);
            viewHolder.issuer.setBackgroundResource(issuer.getSelected() ? R.drawable.shape_market_filter_item_selected : R.drawable.shape_market_filter_item);
            // 给viewHolder中的控件绑定数据
            viewHolder.issuer.setText(issuer.getName());
            viewHolder.issuer.setOnClickListener(view1 -> {
                if (!issuer.getSelected()) {
                    view1.setBackgroundResource(R.drawable.shape_market_filter_item_selected);
                } else {
                    view1.setBackgroundResource(R.drawable.shape_market_filter_item);
                }
                issuer.setSelected(!issuer.getSelected());
            });

            return view;
        }

        public class ViewHolder {
            TextView issuer;
        }
    }

    public class SeriesAdapter extends BaseAdapter {
        private List<Series> seriesList;

        public SeriesAdapter(List<Series> seriesList) {
            this.seriesList = seriesList;
        }

        @Override
        public int getCount() {
            return seriesList.size();
        }

        @Override
        public Object getItem(int i) {
            return seriesList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return seriesList.get(i).getId();
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            // 声明视图持有类实例
            ViewHolder viewHolder;
            if (view == null) {
                // 实例view对象
                view = LayoutInflater.from(getContext()).inflate(R.layout.activity_market_filter_item, viewGroup, false);
                viewHolder = new ViewHolder();
                viewHolder.series = view.findViewById(R.id.filterItem);
                view.setTag(viewHolder);
            } else {
                // 当ListView后面再获取项的视图时
                viewHolder = (ViewHolder) view.getTag();
            }
            // 先取出对应下标的Goods
            Series series = seriesList.get(i);
            // 给viewHolder中的控件绑定数据
            viewHolder.series.setBackgroundResource(series.getSelected() ? R.drawable.shape_market_filter_item_selected : R.drawable.shape_market_filter_item);
            viewHolder.series.setText(series.getName());
            viewHolder.series.setOnClickListener(view1 -> {
                if (!series.getSelected()) {
                    view1.setBackgroundResource(R.drawable.shape_market_filter_item_selected);
                } else {
                    view1.setBackgroundResource(R.drawable.shape_market_filter_item);
                }
                series.setSelected(!series.getSelected());
            });
            return view;
        }

        public class ViewHolder {
            TextView series;
        }
    }

    GridView gridview_goods;
    GridView careGoodsList;
    MarketGoodsAdapter careGoodsAdapter;
    View parentView;
    EditText marketSearch;
    boolean search;
    List<MarketGoods> goodsList;
    List<MarketGoods> careList;
    ImageView marketSearchImg;
    ConstraintLayout searchBox;
    ImageView marketSearchBack;
    TextView marketSearchBtn;
    TextView marketCareBtn;
    TextView marketCollectionBtn;
    LinearLayout marketCategoryBox;
    boolean careOrCollection = false;
    TextView category1;
    TextView category2;
    LinearLayout category3;
    TextView priceText;
    ImageView priceImg;
    TextView category4;
    LinearLayout category5;
    int currentCategory = 1;
    LinearLayout filterBox;
    LinearLayout filterClose;
    LinearLayout filterPriceUp;
    LinearLayout filterPriceDown;
    LinearLayout filterDateUp;
    LinearLayout filterDateDown;
    TextView noData;
    ImageView filterIssuer;
    boolean issuerShow = true;
    ImageView filterSeries;
    boolean seriesShow = true;
    GridView issuerGridView;
    GridView seriesGridView;
    TextView filterReset;
    TextView filterConfirm;
    List<Issuer> issuerList;
    List<Series> seriesList;
    int isFilterPrice = 0;
    int isFilterDate = 0;
    List<Integer> issuers = new ArrayList<>();
    List<Integer> series = new ArrayList<>();
    Handler handler = new Handler();
    Integer pageIndex = 1;
    boolean collectionFinish = false;
    int careIndex = 1;
    boolean careFinish = false;
    boolean loadingIsShow = false;
    boolean collectionInit = false;
    MarketGoodsAdapter goodsAdapter;
    SeriesAdapter seriesAdapter;
    IssuerAdapter issuerAdapter;
    LinearLayout loading;
    ProgressBar progressBar;
    boolean categoryAble = true;
    boolean isSearchIng = false;
    TextView textNoLogin;
    TextView textNoData;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        Bundle bundle = getArguments();
        search = bundle != null ? bundle.getBoolean("search", false) : false;
        if (parentView == null) {
            parentView = inflater.inflate(R.layout.fragment_market, container, false);
            init();
        }
        return parentView;
    }

    @Override
    public void onStart() {
        super.onStart();

    }

    /**
     * 首页进入搜索框获取焦点并且弹出软键盘
     */
    @Override
    public void onResume() {
        if (search) {
            searchBox.setVisibility(View.VISIBLE);
            marketSearch.requestFocus();
            InputMethodManager imm = (InputMethodManager) requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(marketSearch, InputMethodManager.SHOW_IMPLICIT);
        }
        super.onResume();
    }

    /**
     * 点击搜索按钮进行藏品搜索
     */
    public void searchCollections() {
        if (!isSearchIng) {
            goodsList.clear();
            pageIndex = 1;
            collectionFinish = false;
            isSearchIng = true;
            Log.e("INITDATA","2");
            initData();
        }

    }

    public void init() {
        goodsListInit();
        filterInit();
        searchBoxInit();
        initSeries();
        initIssuers();
        replaceTitle();
        replaceCategory(1);
        gridview_goods.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
                    View lastVisibleItemView = gridview_goods.getChildAt(gridview_goods.getChildCount() - 1);
                    if (lastVisibleItemView != null && lastVisibleItemView.getBottom() == gridview_goods.getHeight()) {
                        if (loadingIsShow) return;
                        Log.e("INITDATA","1");
                        initData();
                    }
                }
            }
        });

        careGoodsList.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
                    View lastVisibleItemView = careGoodsList.getChildAt(careGoodsList.getChildCount() - 1);
                    if (lastVisibleItemView != null && lastVisibleItemView.getBottom() == careGoodsList.getHeight()) {
                        if (loadingIsShow) return;
                        initUserFollow();
                    }
                }
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
//        marketSearch.setText("");
//        goodsList.clear();
//        goodsAdapter.notifyDataSetChanged();
    }

    public void goodsListInit() {
        // 绑定控件
        gridview_goods = parentView.findViewById(R.id.gridview_goods);
        careGoodsList = parentView.findViewById(R.id.gridview_CareGoods);
        marketSearch = parentView.findViewById(R.id.maket_search);
        marketSearchImg = parentView.findViewById(R.id.marketSearchImg);
        searchBox = parentView.findViewById(R.id.searchBox);
        marketSearchBack = parentView.findViewById(R.id.maketSearchBack);
        marketSearchBtn = parentView.findViewById(R.id.marketSearchBtn);
        marketCareBtn = parentView.findViewById(R.id.marketCareBtn);
        marketCollectionBtn = parentView.findViewById(R.id.marketCollectionBtn);
        marketCategoryBox = parentView.findViewById(R.id.marketCategoryBox);
        category1 = parentView.findViewById(R.id.category1);
        category2 = parentView.findViewById(R.id.category2);
        category3 = parentView.findViewById(R.id.category3);
        category4 = parentView.findViewById(R.id.category4);
        category5 = parentView.findViewById(R.id.category5);
        filterBox = parentView.findViewById(R.id.filterBox);
        filterClose = parentView.findViewById(R.id.filterClose);
        issuerGridView = parentView.findViewById(R.id.issuerGridView);
        seriesGridView = parentView.findViewById(R.id.seriesGridView);
        filterIssuer = parentView.findViewById(R.id.filterIssuer);
        filterSeries = parentView.findViewById(R.id.filterSeries);
        filterPriceUp = parentView.findViewById(R.id.filterPriceUp);
        filterPriceDown = parentView.findViewById(R.id.filterPriceDown);
        filterDateUp = parentView.findViewById(R.id.filterDateUp);
        filterDateDown = parentView.findViewById(R.id.filterDateDown);
        filterReset = parentView.findViewById(R.id.filterReset);
        filterConfirm = parentView.findViewById(R.id.filterConfirm);
        priceText = parentView.findViewById(R.id.priceText);
        priceImg = parentView.findViewById(R.id.priceImg);
        noData = parentView.findViewById(R.id.noData);
        loading = parentView.findViewById(R.id.loading);
        progressBar = parentView.findViewById(R.id.progressBar);
        textNoLogin = parentView.findViewById(R.id.textNoLogin);
        textNoData = parentView.findViewById(R.id.textNoData);


        // 创建要显示的数据源
        goodsList = new ArrayList<>();
        goodsAdapter = new MarketGoodsAdapter(goodsList, getContext());
        // 给gridview_goods绑定适配器
        gridview_goods.setAdapter(goodsAdapter);
        if (UserUtils.getUser(getContext()) != null) {
            careList = new ArrayList<>();
            careGoodsAdapter = new MarketGoodsAdapter(careList, getContext());
            careGoodsList.setAdapter(careGoodsAdapter);
        }

    }

    public void filterInit() {
        issuerList = new ArrayList<>();
        seriesList = new ArrayList<>();
        issuerAdapter = new IssuerAdapter(issuerList);
        issuerGridView.setAdapter(issuerAdapter);
        GridViewUtils.setGridViewHeightBasedOnChildren(issuerGridView);
        seriesAdapter = new SeriesAdapter(seriesList);
        seriesGridView.setAdapter(seriesAdapter);
        GridViewUtils.setGridViewHeightBasedOnChildren(seriesGridView);

        // 显示隐藏发行方，所属系列
        filterIssuer.setOnClickListener(view -> {
            if (issuerShow) {
                issuerGridView.setVisibility(View.GONE);
                filterIssuer.setImageResource(R.drawable.baseline_market_filter_up);
            } else {
                issuerGridView.setVisibility(View.VISIBLE);
                filterIssuer.setImageResource(R.drawable.baseline_market_filter_down);
            }
            issuerShow = !issuerShow;
        });
        filterSeries.setOnClickListener(view -> {
            if (seriesShow) {
                seriesGridView.setVisibility(View.GONE);
                filterSeries.setImageResource(R.drawable.baseline_market_filter_up);
            } else {
                seriesGridView.setVisibility(View.VISIBLE);
                filterSeries.setImageResource(R.drawable.baseline_market_filter_down);
            }
            seriesShow = !seriesShow;
        });
        filterPriceUp.setOnClickListener(view -> {
            view.setBackgroundResource(R.drawable.shape_market_filter_item_selected);
        });
        filterReset.setOnClickListener(view -> {
            issuerList.forEach((item) -> {
                if (item.getSelected()) {
                    item.setSelected(false);
                }
            });
            seriesList.forEach((item) -> {
                if (item.getSelected()) {
                    item.setSelected(false);
                }
            });
            isFilterPrice = 0;
            isFilterDate = 0;
            replaceFilterDate();
            replaceFilterPrice();
            issuerAdapter.notifyDataSetChanged();
            seriesAdapter.notifyDataSetChanged();
        });
        filterPriceUp.setOnClickListener(view -> {
            if (isFilterPrice == 0 || isFilterPrice == 2) {
                isFilterPrice = 1;
                replaceFilterPrice();
            } else {
                isFilterPrice = 0;
                replaceFilterPrice();
            }
        });
        filterPriceDown.setOnClickListener(view -> {
            if (isFilterPrice == 0 || isFilterPrice == 1) {
                isFilterPrice = 2;
                replaceFilterPrice();
            } else {
                isFilterPrice = 0;
                replaceFilterPrice();
            }
        });
        filterDateUp.setOnClickListener(view -> {
            System.out.println(123);
            if (isFilterDate == 0 || isFilterDate == 2) {
                isFilterDate = 1;
                replaceFilterDate();
            } else {
                isFilterDate = 0;
                replaceFilterDate();
            }
        });
        filterDateDown.setOnClickListener(view -> {
            if (isFilterDate == 0 || isFilterDate == 1) {
                isFilterDate = 2;
                replaceFilterDate();
            } else {
                isFilterDate = 0;
                replaceFilterDate();
            }
        });
        filterConfirm.setOnClickListener(view -> {
            issuers.clear();
            series.clear();
            issuerList.forEach((item) -> {
                if (item.getSelected()) {
                    issuers.add(item.getId());
                }
            });
            seriesList.forEach((item) -> {
                if (item.getSelected()) {
                    series.add(item.getId());
                }
            });
            goodsList.clear();
            pageIndex = 1;
            collectionFinish = false;
            System.out.println(4);
            Log.e("INITDATA","3");
            initData();
            filterBox.setVisibility(View.GONE);
        });
    }
    public void searchBoxInit() {
        // 显示搜索框
        marketSearchImg.setOnClickListener(view -> {
            searchBox.setVisibility(View.VISIBLE);
        });
        // 隐藏搜索框
        marketSearchBack.setOnClickListener(view -> {
            searchBox.setVisibility(View.GONE);
        });
        // 搜索功能
        marketSearchBtn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    marketSearch.clearFocus();
                    view.clearFocus();
                    InputMethodManager imm = (InputMethodManager) requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(view.getWindowToken(),0);
                    searchCollections();
                }

                return true;
            }
        });
        marketCareBtn.setOnClickListener(view -> {
            if (careOrCollection) {
                replaceTitle();
            }
        });
        marketCollectionBtn.setOnClickListener(view -> {
            if (!careOrCollection) {
                replaceTitle();
            }
        });
        category1.setOnClickListener(view -> {
            if (!categoryAble) return;
            if (currentCategory != 1) {
                if (!collectionInit) return;
                categoryAble = false;
                replaceCategory(1);
                pageIndex=1;
                collectionFinish = false;
                goodsList.clear();
                goodsAdapter.notifyDataSetChanged();
                Log.e("INITDATA","4");
                initData();
            }
        });

        category2.setOnClickListener(view -> {
            if (!categoryAble) return;
            if (currentCategory != 2) {
                categoryAble = false;
                replaceCategory(2);
                pageIndex=1;
                collectionFinish = false;
                goodsList.clear();
                goodsAdapter.notifyDataSetChanged();
                Log.e("INITDATA","5");
                initData();
            }
        });
        category3.setOnClickListener(view -> {
            if (!categoryAble) return;
            priceText.setTextColor(Color.rgb(255, 155, 77));
            priceImg.setImageResource(R.drawable.baseline_market_price_sort_selected);
            pageIndex = 1;
            //升序
            if (isFilterPrice == 0 || isFilterPrice == 2) {
                isFilterPrice = 1;
                priceImg.setRotation(180);
                replaceFilterPrice();
                goodsList.clear();
                collectionFinish = false;
                Log.e("INITDATA","6");
                initData();
            } else {
                //降序
                isFilterPrice = 2;
                priceImg.setRotation(360);
                replaceFilterPrice();
                goodsList.clear();
                collectionFinish = false;
                Log.e("INITDATA","7");
                initData();
            }
        });
        category4.setOnClickListener(view -> {
            if (!categoryAble) return;
            if (currentCategory != 4) {
                replaceCategory(4);
            }
        });
        category5.setOnClickListener(view -> {
            if (!categoryAble) return;
            filterBox.setVisibility(View.VISIBLE);
        });
        filterClose.setOnClickListener(view -> {
            filterBox.setVisibility(View.GONE);
        });
    }

    public void replaceTitle() {
        if (careOrCollection) {
            textNoData.setVisibility(View.GONE);
            if (UserUtils.getUser(getContext()) != null) {
                careList.clear();
                careIndex = 1;
                careFinish = false;
                loadingIsShow = false;
                initUserFollow();
                textNoLogin.setVisibility(View.GONE);
            } else {
                textNoLogin.setVisibility(View.VISIBLE);
                Toast.makeText(getContext(), "请先登录", Toast.LENGTH_SHORT).show();
            }
            marketCollectionBtn.setTextSize(14);
            marketCollectionBtn.setTextColor(Color.rgb(122, 119, 119));
            marketCareBtn.setTextColor(Color.BLACK);
            marketCareBtn.setTextSize(20);
            marketCategoryBox.setVisibility(View.GONE);
            careOrCollection = false;
            careGoodsList.setVisibility(View.VISIBLE);
            gridview_goods.setVisibility(View.GONE);
        } else {
            textNoLogin.setVisibility(View.GONE);
            marketCareBtn.setTextSize(14);
            marketCareBtn.setTextColor(Color.rgb(122, 119, 119));
            marketCollectionBtn.setTextColor(Color.BLACK);
            marketCollectionBtn.setTextSize(20);
            marketCategoryBox.setVisibility(View.VISIBLE);
            careOrCollection = true;
            careGoodsList.setVisibility(View.GONE);
            gridview_goods.setVisibility(View.VISIBLE);
            if (!collectionInit) {
                pageIndex = 1;
                Log.e("INITDATA","8");
                initData();
            }
        }
    }

    public void replaceCategory(int id) {
        if (id == 1) {
            category1.setTextColor(Color.rgb(255, 155, 77));
            category2.setTextColor(Color.BLACK);
            category4.setTextColor(Color.BLACK);
        } else if (id == 2) {
            category2.setTextColor(Color.rgb(255, 155, 77));
            category1.setTextColor(Color.BLACK);
            category4.setTextColor(Color.BLACK);
        } else if (id == 4) {
            category4.setTextColor(Color.rgb(255, 155, 77));
            category1.setTextColor(Color.BLACK);
            category2.setTextColor(Color.BLACK);
        }
        currentCategory = id;
    }

    public void replaceFilterPrice() {
        if (isFilterPrice == 1) {
            priceText.setTextColor(Color.rgb(255, 155, 77));
            priceImg.setImageResource(R.drawable.baseline_market_price_sort_selected);
            priceImg.setRotation(180);
            filterPriceUp.setBackgroundResource(R.drawable.shape_market_filter_item_selected);
            filterPriceDown.setBackgroundResource(R.drawable.shape_market_filter_item);
        } else if (isFilterPrice == 2) {
            priceText.setTextColor(Color.rgb(255, 155, 77));
            priceImg.setImageResource(R.drawable.baseline_market_price_sort_selected);
            priceImg.setRotation(360);
            filterPriceDown.setBackgroundResource(R.drawable.shape_market_filter_item_selected);
            filterPriceUp.setBackgroundResource(R.drawable.shape_market_filter_item);
        } else {
            filterPriceUp.setBackgroundResource(R.drawable.shape_market_filter_item);
            filterPriceDown.setBackgroundResource(R.drawable.shape_market_filter_item);
            priceText.setTextColor(Color.BLACK);
            priceImg.setImageResource(R.drawable.baseline_market_price_sort_24);
        }
    }

    public void replaceFilterDate() {
        if (isFilterDate == 1) {
            filterDateUp.setBackgroundResource(R.drawable.shape_market_filter_item_selected);
            filterDateDown.setBackgroundResource(R.drawable.shape_market_filter_item);
        } else if (isFilterDate == 2) {
            filterDateDown.setBackgroundResource(R.drawable.shape_market_filter_item_selected);
            filterDateUp.setBackgroundResource(R.drawable.shape_market_filter_item);
        } else {
            filterDateUp.setBackgroundResource(R.drawable.shape_market_filter_item);
            filterDateDown.setBackgroundResource(R.drawable.shape_market_filter_item);
        }
    }

    public void initData() {
        if (loadingIsShow){
            return;
        }
        //设置缓存
        if (!collectionInit && DBUtils.getAllData("market_goods").getCount() > 0) {
            loadingIsShow=true;
            categoryAble = true;
            setGoodsCache();
            return;
        }
        loading.setVisibility(View.VISIBLE);
        loadingIsShow = true;
        if (collectionFinish) {
            loading.setVisibility(View.GONE);
            loadingIsShow = false;
            isSearchIng = false;
            return;
        }
        new Thread(() -> {
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("searchKey", marketSearch.getText());
            jsonBody.put("category", currentCategory);
            jsonBody.put("priceSort", isFilterPrice);
            jsonBody.put("releaseDateSort", isFilterDate);
            jsonBody.put("issuers", issuers);
            jsonBody.put("series", series);
            jsonBody.put("pageIndex", pageIndex);
            jsonBody.put("pageSize", 10);
            String jsonString = HttpUtils.post("/api/market/list", jsonBody.toJSONString());
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse == null) {
                handler.post(() -> {
                    loading.setVisibility(View.GONE);
                    loadingIsShow = false;
                    isSearchIng = false;
                    categoryAble = true;
                    Toast.makeText(getContext(), "服务器异常", Toast.LENGTH_SHORT).show();
                });
            } else if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                JSONArray jsonRecords = jsonResponse.getJSONArray("value");
                int size = jsonRecords.size();
                if (size == 0) {
                    handler.post(() -> {
                        loading.setVisibility(View.GONE);
                        loadingIsShow = false;
                        isSearchIng = false;
//                        Toast.makeText(getContext(), "暂无可查询的藏品", Toast.LENGTH_SHORT).show();
                        collectionFinish = true;
                    });
                } else {
                    for (int i = 0; i < size; i++) {
                        JSONObject jsonGoods = jsonRecords.getJSONObject(i);
                        MarketGoods goods = new MarketGoods(
                                jsonGoods.getInteger("id"),
                                jsonGoods.getString("image"),
                                jsonGoods.getString("name"),
                                jsonGoods.getInteger("count"),
                                jsonGoods.getFloat("price")
                        );
                        goodsList.add(goods);
                    }
                    handler.post(() -> {
                        loading.setVisibility(View.GONE);
                        loadingIsShow = false;
                        isSearchIng = false;
                        goodsAdapter.notifyDataSetChanged();
                        categoryAble = true;
                    });
                    if (!collectionInit) {
                        collectionInit = true;
                        DBUtils.deleteAllData("market_goods");
                        DBUtils.insertMarketGoodsData(goodsList);
                        categoryAble = true;
                    }
                    if (size == 10) {
                        pageIndex++;
                    } else {
                        collectionFinish = true;
                    }
                }
            } else {
                handler.post(() -> {
                    loading.setVisibility(View.GONE);
                    loadingIsShow = false;
                    isSearchIng = false;
                    categoryAble = true;
                    Toast.makeText(getContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            }
            if (goodsList.size() == 0) {
                handler.post(() -> {
                    textNoData.setVisibility(View.VISIBLE);
                    categoryAble = true;
                });
            } else {
                handler.post(() -> {
                    textNoData.setVisibility(View.GONE);
                    categoryAble = true;
                });
            }
        }).start();
    }

    public void setGoodsCache() {
        goodsList.clear();
        Cursor cursor = DBUtils.getAllData("market_goods");
        while (cursor.moveToNext()) {
            int id = cursor.getInt(0);
            String image = cursor.getString(1);
            String name = cursor.getString(2);
            float price = cursor.getFloat(3);
            int count = cursor.getInt(4);
            goodsList.add(new MarketGoods(id, image, name, count, price));
        }
        cursor.close();
        goodsAdapter.notifyDataSetChanged();
        collectionInit = true;
        new Thread(() -> {
            DBUtils.deleteAllData("market_goods");
            List<MarketGoods> goodsList1 = DBUtils.updateMarketGoodsCache();
            handler.post(() -> {
                goodsList.clear();
                goodsList.addAll(goodsList1);
                goodsAdapter.notifyDataSetChanged();
                loadingIsShow=false;
                pageIndex++;
                initData();
                categoryAble = false;
            });
            DBUtils.insertMarketGoodsData(goodsList1);
        }).start();
    }

    public void initUserFollow() {
        loading.setVisibility(View.VISIBLE);
        loadingIsShow = true;
        if (careFinish) {
            loading.setVisibility(View.GONE);
            loadingIsShow = false;
            return;
        }
        Map<String, String> head = new HashMap<>();
        head.put("Authorization", DeviceUtils.getDeviceID());
        new Thread(() -> {
            String jsonString = HttpUtils.get("/api/user/followGoods/" + careIndex, head);
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse == null) {
                handler.post(() -> {
                    loading.setVisibility(View.GONE);
                    loadingIsShow = false;
                    Toast.makeText(getContext(), "服务器异常", Toast.LENGTH_SHORT).show();
                });
            } else if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                JSONArray jsonRecords = jsonResponse.getJSONArray("value");
                int size = jsonRecords.size();
                if (size == 0) {
                    handler.post(() -> {
                        loading.setVisibility(View.GONE);
                        loadingIsShow = false;
                        textNoLogin.setVisibility(View.VISIBLE);
//                        Toast.makeText(getContext(), "暂无可查询的藏品", Toast.LENGTH_SHORT).show();
                        careFinish = true;
                    });
                } else {
                    textNoLogin.setVisibility(View.VISIBLE);
                    for (int i = 0; i < size; i++) {
                        JSONObject jsonGoods = jsonRecords.getJSONObject(i);
                        MarketGoods goods = new MarketGoods(
                                jsonGoods.getInteger("id"),
                                jsonGoods.getString("image"),
                                jsonGoods.getString("name"),
                                jsonGoods.getInteger("count"),
                                jsonGoods.getFloat("price")
                        );
                        careList.add(goods);
                    }
                    handler.post(() -> {
                        loading.setVisibility(View.GONE);
                        loadingIsShow = false;
                        careGoodsAdapter.notifyDataSetChanged();
                    });
                    if (size == 10) careIndex++;
                    else careFinish = true;
                }
            } else {
                handler.post(() -> {
                    loading.setVisibility(View.GONE);
                    loadingIsShow = false;
                    Toast.makeText(getContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }

    boolean seriesInit = false;
    public void initSeries() {
        if (!issuerInit && DBUtils.getAllData("market_series").getCount()>0){
            setSeriesCache();
            return;
        }
        new Thread(() -> {
            String jsonString = HttpUtils.get("/api/series/list");
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse == null) {
            } else if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                JSONArray jsonRecords = jsonResponse.getJSONArray("value");
                for (int i = 0; i < jsonRecords.size(); i++) {
                    JSONObject jsonGoods = jsonRecords.getJSONObject(i);
                    Series series = new Series(
                            jsonGoods.getInteger("id"),
                            jsonGoods.getString("name")
                    );
                    seriesList.add(series);
                }
                handler.post(() -> {
                    seriesAdapter.notifyDataSetChanged();
                });
                if (!seriesInit) {
                    seriesInit = true;
                    DBUtils.deleteAllData("market_series");
                    DBUtils.insertSeries(seriesList);
                }
            } else {
                handler.post(() -> {
                    Toast.makeText(getContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }
    public void setSeriesCache() {
        seriesList.clear();
        Cursor cursor = DBUtils.getAllData("market_series");
        while (cursor.moveToNext()) {
            int id = cursor.getInt(0);
            String name = cursor.getString(1);
            seriesList.add(new Series(id,name));
        }
        cursor.close();
        seriesAdapter.notifyDataSetChanged();
        seriesInit = true;
        new Thread(() -> {
            DBUtils.deleteAllData("market_series");
            List<Series> series1 = DBUtils.updateMarketSeries();
            handler.post(() -> {
                seriesList.clear();
                seriesList.addAll(series1);
                issuerAdapter.notifyDataSetChanged();
            });
            DBUtils.insertSeries(series1);
        }).start();
    }
    boolean issuerInit = false;
    public void initIssuers() {
        if (!issuerInit && DBUtils.getAllData("market_issuer").getCount()>0){
            setIssuerCache();
            return;
        }
        new Thread(() -> {
            String jsonString = HttpUtils.get("/api/issuer/list");
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse == null) {
            } else if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                JSONArray jsonRecords = jsonResponse.getJSONArray("value");
                for (int i = 0; i < jsonRecords.size(); i++) {
                    JSONObject jsonGoods = jsonRecords.getJSONObject(i);
                    Issuer issuer = new Issuer(
                            jsonGoods.getInteger("id"),
                            jsonGoods.getString("name")
                    );
                    issuerList.add(issuer);
                }
                handler.post(() -> {
                    issuerAdapter.notifyDataSetChanged();
                });
                if (!issuerInit) {
                    issuerInit = true;
                    DBUtils.deleteAllData("market_issuer");
                    DBUtils.insertIssuer(issuerList);
                }
            } else {
                handler.post(() -> {
                    Toast.makeText(getContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }

    public void setIssuerCache() {
        issuerList.clear();
        Cursor cursor = DBUtils.getAllData("market_issuer");
        while (cursor.moveToNext()) {
            int id = cursor.getInt(0);
            String name = cursor.getString(1);
            issuerList.add(new Issuer(id,name));
        }
        cursor.close();
        issuerAdapter.notifyDataSetChanged();
        issuerInit = true;
        new Thread(() -> {
            DBUtils.deleteAllData("market_issuer");
            List<Issuer> issuers1 = DBUtils.updateMarketIssuer();
            handler.post(() -> {
                issuerList.clear();
                issuerList.addAll(issuers1);
                issuerAdapter.notifyDataSetChanged();
            });
            DBUtils.insertIssuer(issuers1);
        }).start();
    }
}